import axios from 'axios';
import qs from 'qs';
import Vue from 'vue';
import {router} from '../router';
import store from '../store';
import { Message } from 'element-ui';


axios.defaults.timeout = 150000;
axios.defaults.baseURL = '';
export let baseUrl = '';
// export let baseUrl = '/api3_test';
if(process.env.NODE_ENV == 'production'){
  // baseUrl = "/api3"
    baseUrl = "/api3_test"
}

axios.interceptors.request.use(
    config => {
        config.headers = {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        }
        return config;
    },
    err => {
        Message.error({ message: '请求超时!' });
        return err
    }
);

axios.interceptors.response.use(
    res => {
        if(res.data.code == -2){
          router.replace({path: '/login', query:{redirect:1}})
        }else if(res.data.code == -1){
          Message.error(res.data.message);
          return res;
        }else{
          return res;
        }
    },
    err => {
        if (err.response.status == 504 || err.response.status == 404) {
            Message.error({ message: '服务器被吃了⊙﹏⊙∥' });
        } else if (err.response.status == 403) {
            Message.error({ message: '权限不足,请联系管理员!' });
        } else {
            Message.error({ message: '未知错误' });
        }
        return err;
    }
)

export function fetch(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        }).then(response => {
            resolve(response);
        }).catch(err => {
            reject(err)
        })
    })
}

export function post(url, data = {}) {
    var qs_data = null;
    if(data.toString() === '[object FormData]'){
      qs_data = data;
    }else{
      qs_data = qs.stringify(data);
    }
    return axios.post(baseUrl + url, qs_data)
}

export function getExport(url, data={}){
  var qs_data = null;
  if(data.toString()){
    qs_data = qs.stringify(data);
  }
  window.open(baseUrl + url + '?' + qs_data)
}



let http = axios.create({
  baseURL: '/',
  timeout: 5000,
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

http.param = (data = {}, contentType = 'application/x-www-form-urlencoded') => {
  return contentType === 'application/x-www-form-urlencoded' ? qs.stringify(data) : (contentType === 'application/json' ? JSON.stringify(data) : data)
}
/**
 * get封装
 * @params:url
 * @params:params
 */
export function httpGet (url, params = {}) {
  return new Promise((resolve, reject) => {
    http.get(
      url, {params: params})
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * post封装
 * @params:url
 * @params:param
 */
export function httpPost (url, param = {}) {
  return new Promise((resolve, reject) => {
    http.post(url, http.param(param))
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}
